// 聊天区
import MessageItem from '@/components/message-item';
import { MessageType } from '@/constants/chat';
import { Flex, Spin } from 'antd';
import {
  // useCreateConversationBeforeUploadDocument,
//   useGetFileIcon,
  // useGetSendButtonDisabled,
  // useSendButtonDisabled,
  useSendNextMessage,
} from './hooks';
import { buildMessageItemReference } from '@/pages/chat/utils';

// import MessageInput from '@/components/message-input';
import PdfDrawer from '@/components/pdf-drawer';
import { useClickDrawer } from '@/components/pdf-drawer/hooks';
import {
  useFetchNextConversation,
//   useGetChatSearchParams,
} from '@/hooks/chat-hooks';
// import { useFetchUserInfo } from '@/hooks/user-setting-hooks';
import useStore from '@/store';
import { buildMessageUuidWithRole } from '@/utils/chat';
import { memo, useEffect, useRef, useState } from 'react';
import styles from './index.less';
import chatService from '@/services/chat-service';
import { chatID, authorization } from '@/constants/chat';

interface IProps {
  controller: AbortController;
  sessionIdIndex: number;
}

const ChatContainer = ({ controller, sessionIdIndex }: IProps) => {
  // const { conversationId } = useGetChatSearchParams();
  const { data: conversation } = useFetchNextConversation();
  console.log('conversation', conversation);
  const {
    // value,
    ref,
    loading,
    sendLoading,
    // derivedMessages,
    // handleInputChange,
    // handlePressEnter,
    regenerateMessage,
    removeMessageById,
    // stopOutputMessage,
  } = useSendNextMessage(controller);

  const { visible, hideModal, documentId, selectedChunk, clickDocumentButton } =
    useClickDrawer();
  // const disabled = useGetSendButtonDisabled();  // 按钮防重提交，提交中禁用按钮
  // const sendDisabled = useSendButtonDisabled(value);
//   useGetFileIcon();

  // const { data: userInfo } = useFetchUserInfo();
  // 使用zustand store
  const { 
    userInfo,
    setUserInfo, 
    chatSession, 
    setChatSession, 
    setChatFirstTime 
  } = useStore();

  const messages = chatSession.chatList || [];
  console.log('messages', messages);
  console.log('💬 ChatContainer 消息列表:', messages.map(msg => ({
    id: msg.ashId,
    role: msg.ashRole,
    contentLength: msg.ashcContent?.length || 0,
    isStreaming: msg.isStreaming,
    timestamp: msg.timestamp
  })));
  
  // 添加强制刷新逻辑
  console.log('🔄 ChatContainer 渲染时间:', Date.now());

  
  // 将获取到的用户信息保存到store
  useEffect(() => {
    if (userInfo && Object.keys(userInfo).length > 0) {
      setUserInfo(userInfo);
    }
  }, [userInfo, setUserInfo]);

  // console.log('chatSession》〉》〉', chatSession);
  // 如果助手和会话为空，则创建会话
  const createChatAndSession = async () => {
    try {
      // 创建会话，设置为初次会话
      setChatFirstTime(true);
      
      // 创建会话，进行会话和用户双向绑定
      const {data} = await chatService.createSessionInChatAssistant({
        authorization: authorization,
        chatId: chatID,
        requestBody: {
          name: "new chat"
        }
      });
      // console.log('createSessionInChatAssistant', data)
      
      const sessionId = data?.data?.data?.id;
      // console.log('createSessionInChatAssistant', data.data);
      
      if (sessionId) {
        // 存储会话ID到store
        setChatSession({
          sessionId,
          chatId: chatID,
        });
        
        // 绑定用户和会话
        await chatService.bindSessionWithMainUser({
          mainUserId: userInfo?.id,
          mainUserName:  userInfo?.auName,
          sessionId,
          chatId: chatID,
        });
        // const sessionId2 = res2?.data?.data?.[0]?.aisId;
          
        //   // 保存会话信息到store
        //   setChatSession({
        //     isFirstChat: false,
        //     sessionId: sessionId2,
        //     chatId: chatID
        //   });
        // console.log('bindSessionWithMainUser', res2);
      }
    } catch (error) {
      console.error('Failed to create chat session:', error);
    }
  }
  // const { createConversationBeforeUploadDocument } =
  //   useCreateConversationBeforeUploadDocument();
    // 第一步，获取用户绑定的聊天助手和其会话Id
    const getChatAndSessionListBindWithMainUser = async () => {
      try {
        const { data } = await chatService.getChatAndSessionListBindWithMainUser({
          MainUserId: userInfo?.id
        });
        // console.log('getChatAndSessionListBindWithMainUser', data);
        
        // 判断是否是初次会话
        const isFirstChat = data?.data?.length === 0;
        
        // 更新会话状态到store
        setChatFirstTime(isFirstChat);
        
        if (isFirstChat) {
          // 初次会话，创建会话
          console.log('首次聊天，创建会话和绑定用户');
          createChatAndSession();
        } else {
          // 继续会话，获取会话ID
          console.log('sessionIdIndex', sessionIdIndex)
          const sessionId = data?.data?.[sessionIdIndex]?.aisId;
          
          // 保存会话信息到store
          setChatSession({
            isFirstChat: false,
            sessionId,
            chatId: chatID
          });
          
          // // 继续聊天，获取历史会话列表
          // const { data: sessionList } = await chatService.getSessionListInChatAssistant({
          //   Authorization: authorization,
          //   ChatId: chatID,
          //   PageIndex: 1,
          //   PageSize: 10000,
          //   id: sessionId // 会话Id
          // });
          // 继续聊天，获取历史会话列表
          // const { data: sessionList } = await chatService.getSessionListInChatAssistant({
          const { data: sessionList } = await chatService.getSessionHistoryRecordList({
            sessionId,
            chatId: chatID,
            itemNum:-5
          });
          console.log('继续聊天，获取历史会话', sessionList);
          // 存储聊天记录到store
          if (sessionList?.data) {
            // 这里也需要对比下，如果之前的数据和现在的一样，就不需要更新
            setChatSession({

              chatList: sessionList.data, // messages 信息在sessionList.data.data[0].messages,
            });
          }
          
          // 然后展示内容 拿到数据，渲染，展示
          // console.log('继续聊天，获取历史会话', sessionList);
        }
      } catch (error) {
        console.error('获取聊天会话信息失败:', error);
        // 出错时默认为初次会话
        setChatFirstTime(true);
      }
    }
    useEffect(() => {
        if(userInfo?.id){
            getChatAndSessionListBindWithMainUser()
        }
    }, [])
   
  // 对话类型发生改变，重新获取聊天记录
  useEffect(() => {
    console.log('useEffect sessionIdIndex', sessionIdIndex)
    getChatAndSessionListBindWithMainUser()
  }, [sessionIdIndex]);
    

  // const renderChatHeader = () => {
  //   if (chatSession?.isFirstChat) {
  //     return <div className="chat-status-indicator">初次对话</div>;
  //   } else {
  //     return <div className="chat-status-indicator">继续对话 - 会话ID: {chatSession?.sessionId?.slice(0, 8)}</div>;
  //   }
  // };

  // 新增：用于滚动到底部的 ref
  const messagesEndRef = useRef<HTMLDivElement>(null);
  // 新增：用于判断是否在底部的 ref
  const containerRef = useRef<HTMLDivElement>(null);
  // 新增：是否自动滚动到底部
  const [autoScroll, setAutoScroll] = useState(true);

  // 监听滚动，判断是否在底部
  useEffect(() => {
    const handleScroll = () => {
      const container = containerRef.current;
      if (!container) return;
      const isAtBottom = container.scrollHeight - container.scrollTop - container.clientHeight < 2;
      setAutoScroll(isAtBottom);
    };
    const container = containerRef.current;
    if (!container) return;
    container.addEventListener('scroll', handleScroll);
    return () => container.removeEventListener('scroll', handleScroll);
  }, []);

  // chatList 变化后，只有在底部时才自动滚动
  useEffect(() => {
    if (autoScroll) {
      messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
    }
  }, [messages, autoScroll]);

  // 直接渲染所有消息（不使用虚拟列表）
  return (
    <div className={styles.containerWrapper}>
      {/* 在顶部显示会话状态指示器 */}
      {/* {renderChatHeader()} */}
      
      <Flex flex={1} className={styles.chatContainer} vertical>
        <Flex flex={1} vertical className={styles.messageContainer}>
          <Spin spinning={loading}>
            <div
              ref={containerRef}
              className="flex flex-col gap-4"
              style={{ width: '100%', overflowY: 'auto', height: '100%' }}
            >
              {messages.map((msg, i) => {
                if (i === messages.length - 1) {
                  // 最新一条消息直接渲染
                  return (
                    <MessageItem
                      loading={
                        msg.role === MessageType.Assistant &&
                        sendLoading &&
                        messages.length - 1 === i
                      }
                      key={buildMessageUuidWithRole(msg)}
                      item={msg}
                      nickname={'xxx'}
                      avatar={'xxx'}
                      avatarDialog={conversation.avatar}
                      reference={buildMessageItemReference(
                        {
                          message: messages,
                          reference: conversation.reference,
                        },
                        msg,
                      )}
                      clickDocumentButton={clickDocumentButton}
                      index={i}
                      removeMessageById={removeMessageById}
                      regenerateMessage={regenerateMessage}
                      sendLoading={sendLoading}
                      isStreaming={msg.isStreaming || false}
                    />
                  );
                }
                // 其它消息直接渲染
                return (
                  <MessageItem
                    loading={false}
                    key={buildMessageUuidWithRole(msg)}
                    item={msg}
                    nickname={'xxx'}
                    avatar={'xxx'}
                    avatarDialog={conversation.avatar}
                    reference={buildMessageItemReference(
                      {
                        message: messages,
                        reference: conversation.reference,
                      },
                      msg,
                    )}
                    clickDocumentButton={clickDocumentButton}
                    index={i}
                    removeMessageById={removeMessageById}
                    regenerateMessage={regenerateMessage}
                    sendLoading={sendLoading}
                    isStreaming={msg.isStreaming || false}
                  />
                );
              })}
              <div ref={messagesEndRef} />
            </div>
          </Spin>
          <div ref={ref} />
        </Flex>
        {/* <MessageInput
          disabled={disabled}
          sendDisabled={sendDisabled}
          sendLoading={sendLoading}
          value={value}
          onInputChange={handleInputChange}
          onPressEnter={handlePressEnter}
          conversationId={conversationId}
          createConversationBeforeUploadDocument={
            createConversationBeforeUploadDocument
          }
          stopOutputMessage={stopOutputMessage}
        ></MessageInput> */}
        
      </Flex>
      <PdfDrawer
        visible={visible}
        hideModal={hideModal}
        documentId={documentId}
        chunk={selectedChunk}
      ></PdfDrawer>
    </div>
  );
};

export default memo(ChatContainer);
